package com.ruyuan2020.im.xxx.second;

import com.ruyuan2020.im.xxx.second.interceptor.Interceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public class HWInvocationHandler  implements InvocationHandler {

    private Object target;

    private List<Interceptor> interceptorList;

    public HWInvocationHandler(Object target, List<Interceptor> interceptorList) {
        this.target = target;
        this.interceptorList = interceptorList != null ? interceptorList : new ArrayList<>();
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //处理多个拦截器
        for (Interceptor interceptor : interceptorList) {
            interceptor.intercept();
        }
        return method.invoke(target, args);
    }

    // Static method to create a proxy instance
    public static Object wrap(Object target, List<Interceptor> interceptorList) {
        HWInvocationHandler handler = new HWInvocationHandler(target, interceptorList);
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                handler
        );
    }
}
